<?php
/**
 * Created by PhpStorm.
 * User: luoshuqi
 * Date: 19-2-15
 * Time: 上午11:55
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class SysToken extends Model
{
    public static function find(string $token): ?SysToken
    {
        return self::query()->with('user')->where('token', $token)->first();
    }

    public function user()
    {
        return $this->belongsTo(SysUser::class);
    }

    /**
     * 生成token
     * @param int $userId
     * @return string
     */
    public static function generate(int $userId): string
    {
        $token = hash_hmac('sha1', $userId . microtime(true) . mt_rand(), uniqid());
        self::query()->forceCreate(['token' => $token, 'user_id' => $userId]);
        return $token;
    }
}